<template>
  <h3>ref使用</h3>
  <div class="flex">
    {{ count }} <el-button type="success" @click="count++">增加</el-button>
  </div>

  <el-input v-model="obj.name"></el-input>
  <el-input v-model="obj2.name"></el-input>
  <el-button :loading="saving" type="warning" @click="assignment"
    >赋值</el-button
  >
  <div>{{ list }}</div>
  <div>{{ obj3.age }}</div>
  <div>
    <el-button type="success" @click="save">保存</el-button>
    <el-button @click="reset">重置</el-button>
  </div>
</template>
<script setup lang="tsx">
import { reactive, ref, watchEffect } from "vue";
const count = ref(0);
// 虽然表面上是ref实际上走的是reactive
const info = {
  name: "张三",
  id: '',
  eat() {
    alert("张三爱吃饭");
  },
};
const obj = ref({ ...info });
const obj2 = reactive({
  name: "张三2",
  eat() {
    alert("张三爱吃饭");
  },
});
const obj3 = {
  age: 10,
};
const list = ref([
  {
    name: "张三",
  },
]);
const saving = ref(false);
watchEffect(() => {
  console.log(count.value);
});
function assignment() {
  if (saving.value) {
    return;
  }
  saving.value = true;
  obj.value.id = "1";
  list.value.push({
    name: "zhangsan" + Math.random().toFixed(2),
  });
  obj3.age = Math.floor(Math.random() * 100);
  setTimeout(() => {
    saving.value = false;
  }, 500);
}
function save() {
  console.log("obj.value", obj.value);
  console.log("obj2", obj2);
  console.log("obj3", obj3);
}
// 重置
function reset() {
  Object.assign(obj.value, info);
}
</script>
<style lang="scss" scoped>
.flex {
  display: flex;
  column-gap: 10px;
}
.el-input {
  max-width: 200px;
}
</style>
